const router = require('koa-router')()
const { exec } = require('../utils/exec')
const { SuccessModel, FailModel } = require('../utils/resModel')

// 查
router.get('/api/blogs/list', async (ctx, next) => {
  const { page = 1, size = 5 } = ctx.query
  try {
    const sql = `select * from blogs inner join users where users.id = blogs.userId limit ? offset ?`
    const data = await exec(sql, [size * 1, (page - 1) * size])
    ctx.body = new SuccessModel('success', data)
  } catch (err) {
    ctx.body = new FailModel('fail', err)
  }
})
// 增
router.post('/api/blogs/list', async (ctx, next) => {
  const { title, content, userId } = ctx.request.body
  try {
    const sql = `insert into blogs (title, content, userId) values (?, ?, ?)`
    const data = await exec(sql, [title, content, userId])
    if (data.affectedRows) {
      ctx.body = new SuccessModel('success', data)
    } else {
      ctx.body = new FailModel('fail')
    }
  } catch (err) {
    ctx.body = new FailModel('fail', err)
  }
})

// 改
router.put('/api/blogs/list', async (ctx, next) => {
  const { title, content, blogId } = ctx.request.body
  try {
    const sql = `update blogs set title=?, content=? where blogId = ?`
    const data = await exec(sql, [title, content, blogId])
    if (data.affectedRows) {
      ctx.body = new SuccessModel('success', data)
    } else {
      ctx.body = new FailModel('修改失败')
    }
  } catch (err) {
    ctx.body = new FailModel('fail', err)
  }
})
// 删
// router.delete('/api/blogs/list', async (ctx, next) => {
//   const { blogId } = ctx.query
//   try {
//     const sql = `delete from blogs where blogId=?`
//     const data = await exec(sql, [blogId])
//     if (data.affectedRows) {
//       ctx.body = new SuccessModel('success', data)
//     } else {
//       ctx.body = new FailModel('fail')
//     }
//   } catch (err) {
//     ctx.body = new FailModel('fail', err)
//   }
// })
// 批量删除

// 操作 code表=>
router.delete('/api/blogs/list', async (ctx, next) => {
  const { ids } = ctx.request.body
  let sql = `delete from blogs where 1+1 `
  let deleteData
  if (Array.isArray(ids)) {
    // 删除多个
    sql += `and codeId in (${ids.join(',')})`
    deleteData = await exec(sql)
  } else {
    sql += `and codeId=?`
    deleteData = await exec(sql, [ids])
  }
  ctx.body = new SuccessModel({ deleteData, sql })
})

module.exports = router
